import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as loginApi, getUserInfo } from '@/api/auth'
import type { LoginForm, UserInfo } from '@/types/auth'

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string>('')
  const userInfo = ref<UserInfo | null>(null)
  
  const isAuthenticated = computed(() => !!token.value)
  
  const login = async (loginForm: LoginForm) => {
    try {
      const response = await loginApi(loginForm)
      token.value = response.token
      userInfo.value = response.user
      localStorage.setItem('token', token.value)
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
      return response
    } catch (error) {
      throw error
    }
  }
  
  const logout = () => {
    token.value = ''
    userInfo.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }
  
  const checkAuthStatus = () => {
    const savedToken = localStorage.getItem('token')
    const savedUserInfo = localStorage.getItem('userInfo')
    
    if (savedToken && savedUserInfo) {
      token.value = savedToken
      userInfo.value = JSON.parse(savedUserInfo)
    }
  }
  
  const updateUserInfo = async () => {
    if (token.value) {
      try {
        const user = await getUserInfo()
        userInfo.value = user
        localStorage.setItem('userInfo', JSON.stringify(user))
      } catch (error) {
        console.error('获取用户信息失败:', error)
      }
    }
  }
  
  return {
    token,
    userInfo,
    isAuthenticated,
    login,
    logout,
    checkAuthStatus,
    updateUserInfo
  }
})